import { useEffect, useRef, useState } from "react";
import { BasicForm, useForm, FormSchema } from "@/components/Form";
import { useTranslation } from "react-i18next";
import {
	patientExamDeptExamCount,
	patientExamPage,
	outPatientsGet,
	patientHealthCheckPatientAdd,
	outpatientsCreate
} from "@/api/MedicalExamination";
import { createPatients, get_patients, put_patients } from "@/api/components/patientInformation";
import { BasicTable, useTable } from "@/components/Table";
import { TransferPatient } from "@/components/ViewComponents/TransferPatient";
import { useDrawer } from "@/components/Drawer";
import moment from "moment";
import Toolbar from "@/components/ViewComponents/Toolbar";
import { message } from "antd";
import "./index.less";
import { getSimpleDeptList } from "@/api/system/dept";
import OrderDetails from "./components/orderDetails";
export default function patient_registration() {
	const { t } = useTranslation();
	const currentMoment = moment();
	const utilA = "viewComponents.patientInformation";
	// 患者信息表单
	const thPatientInfoForm: FormSchema[] = [
		{
			label: t("felix_ui.pat_cardno"),
			field: "patCardno",
			component: "InputSearch",
			componentProps: {
				onSearch: (val: string) => {
					if (val) getPatientInfo(val);
				},
				allowClear: true
			},
			rules: [
				{
					required: true,
					message: t("felix_ui.please_enter_cardnum")
				}
			],
			colProps: { span: 24 }
		},
		{
			label: t("felix_ui.full_name"),
			field: "fullName",
			component: "Input"
		},
		{
			label: t("felix_ui.age"),
			field: "age",
			component: "Input"
		},
		{
			label: t("felix_ui.citizen_id"),
			field: "citizenId",
			component: "Input",
			rules: [
				{
					required: true,
					message: t("viewComponents.patientInformation.pleaseEnterID")
				}
			]
		},
		{
			label: t("felix_ui.gender"),
			field: "gender",
			component: "Select",
			componentProps: {
				options: [
					{
						label: t("felix_ui.woman"),
						value: "F"
					},
					{
						label: t("felix_ui.man"),
						value: "M"
					},
					{
						label: t("felix_ui.other"),
						value: "Other"
					}
				]
			}
		},
		{
			label: t("felix_ui.date_of_birth"),
			field: "birthday",
			component: "DatePicker",
			rules: [{ type: "object" as const, required: true, message: "Please select time!" }],
			componentProps: {
				format: "YYYY-MM-DD"
			}
		},
		{
			label: t("felix_ui.ethnicity"),
			field: "ethnicity",
			component: "Input"
		},
		{
			label: t("felix_ui.pat_address"),
			field: "addrCity",
			component: "Input"
		},
		{
			label: t("felix_ui.n_industry"),
			field: "occupation",
			component: "Input"
		},
		{
			label: t("felix_ui.phone_numb"),
			field: "phoneNumb",
			component: "Input"
		},
		{
			label: t("felix_ui.grp_email"),
			field: "emailAddr",
			component: "Input",
			rules: [{ required: true, message: t("felix_ui.please_enter_email"), type: "email" }]
		},
		{
			label: t("felix_ui.house_number"),
			field: "addrHouseno",
			component: "Input"
		},
		{
			label: t("felix_ui.province_city"),
			field: "addrProvince",
			component: "Input"
		}
	];
	// 配置form
	const [
		formPatient_synthesis,
		{ setFieldsValue: setFieldsValueFn, validateFields: validateFieldsFn, resetFields: resetFieldsFn }
	] = useForm({
		schemas: thPatientInfoForm,
		showActionButtonGroup: false,
		labelWidth: 120,
		baseColProps: { span: 12 }
	});
	const [deptId, setDeptId] = useState("");
	const formSchemaRight: FormSchema[] = [
		{
			label: t("felix_ui.dt_date"),
			field: "dtDate",
			component: "DatePicker"
		},
		{
			label: t("felix_ui.dt_time"),
			field: "dtTime",
			component: "TimePicker"
		},
		{
			label: t("felix_ui.clinic_name"),
			field: "cliniName",
			component: "ApiSelect",
			componentProps: {
				api: getSimpleDeptList,
				labelField: "name",
				valueField: "id",
				onChange: (id: any) => {
					setDeptId(id);
				}
			}
		},
		{
			label: t("felix_ui.pat_subject"),
			field: "patSubject",
			component: "Select",
			componentProps: {
				options: [
					{
						label: t("MedicalExamination.outpatientExpenses.charge.cash"),
						value: 1
					},
					{
						label: t("MedicalExamination.outpatientExpenses.charge.socialSecurity"),
						value: 2
					},
					{
						label: t("MedicalExamination.outpatientExpenses.charge.bankCard"),
						value: 3
					},
					{
						label: t("MedicalExamination.outpatientExpenses.charge.others"),
						value: 4
					}
				]
			}
		},
		{
			label: t("felix_ui.pat_cardno"),
			field: "patCardno",
			component: "Input"
		},
		{
			label: t("felix_ui.from"),
			field: "from",
			component: "DatePicker"
		},
		{
			label: t("felix_ui.to"),
			field: "to",
			component: "DatePicker"
		},
		{
			label: t("felix_ui.hitech_person"),
			field: "hitechPerson",
			component: "DatePicker"
		},
		{
			label: t("felix_ui.maternal_care"),
			field: "maternalCare",
			component: "DatePicker"
		},
		{
			label: t("felix_ui.out_of_category"),
			field: "outOfCategory",
			component: "DatePicker"
		},
		{
			label: t("felix_ui.at_least_5yr"),
			field: "atLeast5yr",
			component: "DatePicker"
		},
		{
			label: t("felix_ui.exempted_person"),
			field: "exemptedPerson",
			component: "DatePicker"
		},
		{
			label: t("felix_ui.copmt_exempted"),
			field: "copmtExempted",
			component: "Checkbox"
		}
	];
	const [registerFormRight, { setFieldsValue, validateFields, resetFields }] = useForm({
		schemas: formSchemaRight,
		labelWidth: 130,
		baseColProps: { span: 12 }
	});
	const columnHistory = [
		{
			title: t("MedicalExamination.patientRegistration.examId"),
			dataIndex: "examId"
		},
		{
			title: t("MedicalExamination.patientRegistration.serviceName"),
			dataIndex: "serviceName"
		},
		{
			title: t("MedicalExamination.patientRegistration.deptName"),
			dataIndex: "deptName"
		},
		{
			title: t("common.createdTime"),
			dataIndex: "createdTime"
		}
	];
	const [registerHistoryTable, { reload: reloadHistory }] = useTable({
		columns: columnHistory,
		api: patientExamPage,
		maxHeight: 200
	});

	const columnStatistic = [
		{
			title: t("MedicalExamination.patientRegistration.deptId"),
			dataIndex: "deptId"
		},
		{
			title: t("MedicalExamination.patientRegistration.deptName"),
			dataIndex: "deptName"
		},
		{
			title: t("MedicalExamination.patientRegistration.finishNumb"),
			dataIndex: "finishNumb"
		},
		{
			title: t("MedicalExamination.patientRegistration.waitNumb"),
			dataIndex: "waitNumb"
		},
		{
			title: t("MedicalExamination.patientRegistration.totalNumb"),
			dataIndex: "totalNumb"
		}
	];
	const [registerStatisticTable] = useTable({
		columns: columnStatistic,
		api: patientExamDeptExamCount,
		maxHeight: 200
	});
	const [registerDrawer, { openDrawer }] = useDrawer();
	const [registerTransferDrawer, { openDrawer: openDrawerTransfer }] = useDrawer();
	const values = useRef(null);
	const [patientInfo, setPatientInfo] = useState<Recordable>({});

	/** Function */
	const getPatientInfo = async (patCardno: string) => {
		const res = await get_patients({ patCardno });
		if (res) {
			setPatientInfo(res);
			setFieldsValueFn({
				...res,
				birthday: moment(res.birthday)
			});
		} else {
			resetFieldsFn(thPatientInfoForm.slice(1, thPatientInfoForm.length).map((item: any) => item.field));
			resetFields();
		}
	};
	const handleSubmitRegistration = async () => {
		const loading = message.loading(t("common.saveLoading"));
		try {
			await patientHealthCheckPatientAdd({
				opmOutpatients: values.current,
				patientExam: {}
			});
			console.log("patientInfo", patientInfo);
			let value = await validateFieldsFn();
			if (value.birthday) value.birthday = value.birthday.split(" ")[0];
			if (Object.keys(patientInfo).length === 0) {
				await createPatients(value);
			} else {
				value.patientId = patientInfo.patientId;
				await put_patients(value);
			}

			loading();
			message.success(t("common.saveSuccessText"));
		} catch (err) {
			loading();
			message.error("save fail!");
		}
	};
	const arrOutpatients = async (value: any) => {
		console.log(deptId);
		const res = await outpatientsCreate({
			deptId: 178,
			...value,
			...patientInfo
		});
		console.log(res);
		openDrawer(true, {
			res,
			handleSubmitRegistration
		});
	};
	const handlerToolbarAction = async (key: string) => {
		const valueForm = await validateFields();
		values.current = valueForm;
		switch (key) {
			case "save":
				arrOutpatients(valueForm);
				break;
			case "transfer":
				openDrawerTransfer(true, {
					record: patientInfo
				});
				break;
		}
	};
	/** Request */
	const getOutPatientInfo = async (patientInfo: Recordable) => {
		if (!(patientInfo && patientInfo.patientId)) return;
		const res = await outPatientsGet({
			patientId: patientInfo.patientId
		});
		if (res) {
			setFieldsValue({
				...res
			});
		} else {
			setFieldsValue({
				dtDate: currentMoment,
				dtTime: currentMoment,
				from: currentMoment,
				to: currentMoment,
				hitechPerson: currentMoment,
				maternalCare: currentMoment,
				outOfCategory: currentMoment,
				atLeast5yr: currentMoment,
				exemptedPerson: currentMoment,
				copmtExempted: currentMoment
			});
		}
	};

	/** Effect */

	useEffect(() => {
		getOutPatientInfo(patientInfo);
		reloadHistory({
			searchInfo: {
				patCardno: patientInfo.patCardno
			}
		});
	}, [patientInfo]);

	return (
		<div className="patient_registration page">
			<div className="page-content">
				<div className="flex patient_registration-form">
					<div className="block">
						<div className="block-label">Ⅰ.{t(`${utilA}.administration`)}</div>
						<BasicForm register={formPatient_synthesis} labelWrap={true}></BasicForm>
					</div>
					<div className="block ml-2">
						<div className="block-label">Ⅱ.{t("felix_ui.reg_for_exam")}</div>
						<BasicForm labelWrap={true} register={registerFormRight}></BasicForm>
					</div>
				</div>
				<div className="flex mt-2 patient_registration-table">
					<div className="block">
						<div className="block-label">Ⅲ.{t("felix_ui.patient_medical_history")}</div>
						<BasicTable className="content-left-table" register={registerHistoryTable}></BasicTable>
					</div>
					<div className="block ml-2">
						<div className="block-label">Ⅳ.{t("felix_ui.clinic_patients_examined_statistics")}</div>
						<BasicTable className="content-left-table" register={registerStatisticTable}></BasicTable>
					</div>
				</div>
				<TransferPatient register={registerTransferDrawer}></TransferPatient>
			</div>
			<OrderDetails register={registerDrawer}></OrderDetails>
			<Toolbar btnList={["save", "transfer"]} action={handlerToolbarAction} />
		</div>
	);
}
